<template>
  <div id="root">
    <div class="upload">
      <div class="title"><span>上传素材</span></div>
      <input type="file" class="file" multiple accept="image/*" @change="upload" />
    </div>
    <div class="description">上传素材后，点击将其加入画布中</div>
    <div id="imgBox">
      <ul class="imgUl">
        <li v-for="(url, index) in imgUrlList" :key="index">
          <img :src="url" @click="addImgLayers(url)" />
          <div class="delete" @click="deleteImg(index)">×</div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapState } from 'vuex'
export default {
  name: 'material',
  data () {
    return {
      imgList: []
    }
  },
  props: [],
  computed: {
    ...mapState(['imgUrlList'])
  },
  methods: {
    // 素材上传事件
    upload (e) {
      //  e.target指向事件执行时鼠标所点击区域的那个元素
      for (let item of e.target.files) {
        const _this = this
        let reader = new FileReader()
        // readAsDataURL方法可以将上传的图片格式转为base64,然后在存入到图片路径,这样就可以上传任意位置的图片
        reader.readAsDataURL(item)
        reader.addEventListener('load', function () {
          _this.addImg(this.result)
        })
      }
    },

    // 向素材区中添加与删除素材事件
    ...mapMutations({ addImg: 'addImgUrl', deleteImg: 'deleteImgUrl' }),
    // 向画布添加素材
    addImgLayers (url) {
      this.$store.state.canvasData.addLayer('image', url)
    }
  }
}
</script>

<style scoped>
#root {
  /* margin: 2px 0 0 2px; */
  /* border: 1px solid #d6d7de; */
  width: 23.86vw;
  height: 85vh;
}

/* 上传素材框样式开始 */
.upload {
  width: 18vw;
  height: 4.4vh;
  background-color: #f5c2ca;
  border-radius: 1vh;
  margin: 0 auto;
  margin-top: 3.15vh;
}
.upload:hover {
  background-color: rgba(135, 206, 235, 1);
}
.title {
  width: 18vw;
  height: 4.4vh;
  display: flex;
  justify-content: center;
  position: absolute;
}
.title > span {
  align-self: center;
  user-select: none;
}
.file {
  width: 18vw;
  height: 4.4vh;
  opacity: 0;
}
/* 上传素材框样式结束 */

.description {
  text-align: center;
  font-size: 0.57vw;
  color: #767676;
}

/* 素材样式开始 */
#imgBox {
  width: 23.86vw;
  height: 83vh;
  margin-top: 0.633vh;
  border-top: 1px solid #d6d7de;
  overflow-y: scroll;
}
::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}

.imgUl {
  display: flex;
  flex-wrap: wrap;
  padding: 0;
}
.imgUl > li {
  width: 5.76vw;
  height: 5.76vw;
  list-style: none;
  margin-left: 1.55vw;
  margin-top: 3.16vh;
  position: relative;
}
.imgUl > li > img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
/* 删除按钮样式 */
.delete {
  position: absolute;
  right: 0;
  top: 0;
  width: 1.65vw;
  height: 1.65vw;
  text-align: center;
  line-height: 1.65vw;
  font-size: 1.234vw;
  background-color: rgba(255, 255, 255, 0.5);
  user-select: none;
  cursor: pointer;
  opacity: 0;
}
.delete:hover {
  background-color: rgba(31, 31, 31, 0.5);
  color: white;
}
.imgUl > li:hover .delete {
  opacity: 1;
}
/* 素材样式结束 */
</style>
